﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Excel;
using ECCSystem.BizRule;
using System.IO;
using ECCSystem.CheckClass;
namespace ECCSystem.Reports
{
	public partial class frmCategoryReport : Form
	{
		public frmCategoryReport()
		{
			InitializeComponent();
		}
		DataSet objDS = new DataSet();
		BizRule.ClsReports objBRReports;
		BizRule.ClsCommon objCommon;
		//BizRule.ClsUserMaintenance objBROperator;

		private void frmMailCheckReport_Load(object sender, EventArgs e)
		{
			ReadXML.ReadXml(this);
			dtpFrom.Text = DateTime.Now.ToShortDateString();
			dtpTo.Text = DateTime.Now.ToShortDateString();
			SetColumn();
		}

		private void btnCreate_Click(object sender, EventArgs e)
		{
			if (this.CheckDate() == false)
			{
				MessageBox.Show("終了日付は開始日付より遅い。", "ECC Information");
				return;
			}
			btnCreate.Enabled = false;

			//open data source
			ClsUserMaintenance objClsUserMaintenance  = new ClsUserMaintenance();
			objDS = (DataSet)objClsUserMaintenance.GetList();
			if (objDS.Tables[0].Rows.Count <= 0)
			{
				MessageBox.Show("データ無し。", "ECC Information");
				btnCreate.Enabled = true;
				dgvShow.DataSource = null;
				return;
			}
			else
			{

				BindDate(objDS.Tables[0]);
			}

			////create report
			//this.CreateExcel();

			btnCreate.Enabled = true;
		}

		//Check start date less than end date
		private bool CheckDate()
		{
			if (dtpFrom.Value > dtpTo.Value)
			{
				return false;
			}
			else
			{
				return true;
			}
		}

		private void SetColumn()
		{
			ClsMailCategory objClsMailCategory = new ClsMailCategory();
			DataSet objDataSet = (DataSet)objClsMailCategory.GetList();

			for (int i = 0; i < objDataSet.Tables[0].Rows.Count; i++)
			{
				int intAddColumn = dgvShow.Columns.Add("Category_Name" + i, objDataSet.Tables[0].Rows[i]["Category_Name"].ToString());
				dgvShow.Columns[intAddColumn].Tag = objDataSet.Tables[0].Rows[i]["CategoryScore_KeyID"].ToString();
				dgvShow.Columns[intAddColumn].DefaultCellStyle.Format = "N2";
				dgvShow.Columns[intAddColumn].Width = 150;
			}
		}

		private void BindDate(System.Data.DataTable objDataTable)
		{
			dgvShow.Rows.Clear();
			for (int i = 0; i < objDataTable.Rows.Count; i++)
			{
				int intAddRow = dgvShow.Rows.Add();
				dgvShow.Rows[intAddRow].Cells["LoginID"].Value = objDataTable.Rows[i]["LoginID"].ToString();
				dgvShow.Rows[intAddRow].Cells["UserName"].Value = objDataTable.Rows[i]["UserName"].ToString();
			}


			for (int j = 2; j < dgvShow.Columns.Count; j++)
			{
				objBRReports = new ClsReports();
				objDS = (DataSet)objBRReports.CategoryReportReport(dtpFrom.Value, dtpTo.Value, dgvShow.Columns[j].Tag.ToString());

				for (int i = 0; i < objDS.Tables[0].Rows.Count; i++)
				{
					for (int k = 0; k < dgvShow.Rows.Count; k++)
					{
						if (dgvShow.Rows[k].Cells["LoginID"].Value.ToString() == objDS.Tables[0].Rows[i]["LoginID"].ToString())
						{
							dgvShow.Rows[k].Cells[j].Value = objDS.Tables[0].Rows[i]["PercentCount"];
							break;
						}
					}
				}
				objBRReports = null;
				objDS.Clear();
			}

		}

		#region "Excel"
		//excel operation(open,fill,quit)
		private void CreateExcel()
		{
			Excel.ApplicationClass objExlApp = new Excel.ApplicationClass();
			Excel.Workbook theWookbook = null;
			Excel.Worksheet theWookSheet = null;
			objCommon = new ECCSystem.BizRule.ClsCommon();
			try
			{
			    objExlApp.Visible = false;

			    object objMissing = System.Reflection.Missing.Value;
			    StringBuilder strSavePath = new StringBuilder();
			    strSavePath.Append("C:\\ECCReport\\");
			    //if strSavePath is not existing,create the path
			    if (Directory.Exists(strSavePath.ToString()) == false)
			    {
			        Directory.CreateDirectory(strSavePath.ToString());
			    }

			    StringBuilder strTemplatePath = new StringBuilder();
			    //Excel template path
			    strTemplatePath.Append(System.Windows.Forms.Application.StartupPath);
				strTemplatePath.Append("\\CategoryReport.xls");



			    //if this template is existing or not
			    if (File.Exists(strTemplatePath.ToString()) == false)
			    {
			        MessageBox.Show("レポートのテンプレートファイルが見つかりません。", "ECC Information");
			        //quit excel object
			        objCommon.QuitExcelApp(objExlApp, theWookbook, theWookSheet, null);
			        System.GC.Collect();
			        btnExcel.Enabled = true;
			        return;
			    }
			    //open the excel template
                theWookbook = objExlApp.Workbooks.Open(strTemplatePath.ToString(), objMissing, objMissing, objMissing, objMissing, objMissing,
                                         objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing);
			    //get the first sheet
			    theWookSheet = (Excel.Worksheet)theWookbook.Worksheets[1];

			    //fill data into excel
			    theWookSheet.Cells[2, 1] = dtpFrom.Value.Date.ToString("yyyy/MM/dd") + "-" + dtpTo.Value.Date.ToString("yyyy/MM/dd");

				for (int i = 2; i < dgvShow.Columns.Count; i++)
				{
					theWookSheet.Cells[4, 1 + i] = dgvShow.Columns[i].HeaderText;
				}

				for (int i = 0; i <  objDS.Tables[0].Rows.Count; i++)
				{
					theWookSheet.Cells[i + 5, "A"] = objDS.Tables[0].Rows[i]["LoginID"].ToString();
					theWookSheet.Cells[i + 5, "B"] = objDS.Tables[0].Rows[i]["UserName"].ToString();
				}

				int intUserCount = objDS.Tables[0].Rows.Count;

				for (int j = 2; j < dgvShow.Columns.Count; j++)
				{
					objBRReports = new ClsReports();
					objDS = (DataSet)objBRReports.CategoryReportReport(dtpFrom.Value, dtpTo.Value, dgvShow.Columns[j].Tag.ToString());

					for (int i = 0; i < objDS.Tables[0].Rows.Count; i++)
					{
						for (int k = 0; k < intUserCount; k++)
						{
							if (clsUICheck.NullToString(theWookSheet.get_Range(theWookSheet.Cells[k + 5, "A"], theWookSheet.Cells[k + 5, "A"]).Value2) 
									== objDS.Tables[0].Rows[i]["LoginID"].ToString())
							{
								theWookSheet.Cells[k + 5, j + 1] = objDS.Tables[0].Rows[i]["PercentCount"];
								break;
							}
						}
					}
					objBRReports = null;
					objDS.Clear();
				}

			    //set excel report save path and name
				//strSavePath.Append("CategoryReport" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString());
				//strSavePath.Append(DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".xls");

				strSavePath.Append("Category対応比例" + dtpFrom.Value.Date.ToString("yyyy-MM-dd") + "-" + dtpTo.Value.Date.ToString("yyyy-MM-dd"));

				if (File.Exists(strSavePath.ToString() + ".xls") == true)
				{
					File.Delete(strSavePath.ToString() + ".xls");
				}

			    //if the report has existed or not
			    if (File.Exists(strSavePath.ToString()) == true)
			    {
			        MessageBox.Show("このファイルがもう存在しました！", "ECC Information");
			        //quit excel object
			        objCommon.QuitExcelApp(objExlApp, theWookbook, theWookSheet, null);
			        System.GC.Collect();
			        btnExcel.Enabled = true;
			        return;
			    }

			    //save the report
                theWookbook.SaveAs(strSavePath.ToString(), objMissing, objMissing, objMissing, objMissing, objMissing,
                    Excel.XlSaveAsAccessMode.xlNoChange, objMissing, objMissing, objMissing, objMissing);
			    //prompt save success
			    MessageBox.Show("操作成功しました。", "ECC Information");

			    //quit excel object
			    objCommon.QuitExcelApp(objExlApp, theWookbook, theWookSheet, null);
			    System.GC.Collect();
			    this.Close();
			}
			catch (Exception ex)
			{
			    //quit excel object
			    objCommon.QuitExcelApp(objExlApp, theWookbook, theWookSheet, null);
			    System.GC.Collect();

			    //MessageBox.Show(ex.ToString(), "ECC Catch Error");
			    btnExcel.Enabled = true;
			}
		}
		#endregion

		private void btnExcel_Click(object sender, EventArgs e)
		{
			if (this.CheckDate() == false)
			{
				MessageBox.Show("終了日付は開始日付より遅い。", "ECC Information");
				return;
			}
			objBRReports = new ECCSystem.BizRule.ClsReports();
			ClsUserMaintenance objClsUserMaintenance = new ClsUserMaintenance();
			objDS = (DataSet)objClsUserMaintenance.GetList();
			if (objDS.Tables[0].Rows.Count <= 0)
			{
				MessageBox.Show("データ無し。", "ECC Information");
				btnCreate.Enabled = true;
				dgvShow.DataSource = null;
				return;
			}

			btnExcel.Enabled = false;
			this.CreateExcel();
			btnExcel.Enabled = true;
		}

		private void frmCategoryReport_FormClosing(object sender, FormClosingEventArgs e)
		{
			ReadXML.SaveXml(this);
		}
	}
}